package com.simon.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simon.train.business.domain.DailyTrainSeat;
import com.simon.train.business.domain.DailyTrainSeatExample;
import com.simon.train.business.domain.TrainSeat;
import com.simon.train.business.domain.TrainStation;
import com.simon.train.business.dto.DailyTrainSeatQueryDto;
import com.simon.train.business.dto.DailyTrainSeatSaveDto;
import com.simon.train.business.mapper.DailyTrainSeatMapper;
import com.simon.train.business.vo.DailyTrainSeatQueryVO;
import com.simon.train.common.util.SnowUtil;
import com.simon.train.common.vo.PageVO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DailyTrainSeatService {

    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainSeatService.class);

    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;

    @Resource
    private TrainSeatService trainSeatService;

    @Resource
    private TrainStationService trainStationService;

    /**
     * 根据日期，列车id，座位类型以及车厢号来查询相应的座位
     * @param date
     * @param trainCode
     * @param seatType
     * @param carriageIndex
     * @return
     */
    public List<DailyTrainSeat> selectByDailyTrainCarriageIndex(Date date, String trainCode, String seatType, Integer carriageIndex){
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.setOrderByClause("carriage_seat_index asc");
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andSeatTypeEqualTo(seatType)
                .andCarriageIndexEqualTo(carriageIndex);
        List<DailyTrainSeat> seatList = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);
        return seatList;
    }

    public void SaveDailyTrainSeat(DailyTrainSeatSaveDto dailyTrainSeatSaveDto){
        DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(dailyTrainSeatSaveDto, DailyTrainSeat.class);
        if (ObjectUtil.isNull(dailyTrainSeat.getId())){
            //对于首次保存 也就是新增 需要对字段单独做处理
            dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
            DateTime time = DateTime.now();
            dailyTrainSeat.setCreateTime(time);
            dailyTrainSeat.setUpdateTime(time);
            dailyTrainSeatMapper.insert(dailyTrainSeat);
        } else {
            dailyTrainSeat.setUpdateTime(DateTime.now());
            dailyTrainSeatMapper.updateByPrimaryKey(dailyTrainSeat);
        }

    }

    public PageVO<DailyTrainSeatQueryVO> QueryDailyTrainSeatList(DailyTrainSeatQueryDto dailyTrainSeatQueryDto){
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.setOrderByClause("date desc, train_code asc, carriage_index asc, carriage_seat_index asc");
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria();

        if(ObjectUtil.isNotEmpty(dailyTrainSeatQueryDto.getCode())){
            criteria.andTrainCodeEqualTo(dailyTrainSeatQueryDto.getCode());
        }
        if(ObjectUtil.isNotNull(dailyTrainSeatQueryDto.getDate())){
            criteria.andDateEqualTo(dailyTrainSeatQueryDto.getDate());
        }

        LOG.info("当前请求的页码：{}", dailyTrainSeatQueryDto.getPage());
        LOG.info("每页条数：{}", dailyTrainSeatQueryDto.getPageSize());

        PageHelper.startPage(dailyTrainSeatQueryDto.getPage(),dailyTrainSeatQueryDto.getPageSize());
        List<DailyTrainSeat> dailyTrainSeatList = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);

        PageInfo<DailyTrainSeat> pageInfo = new PageInfo<>(dailyTrainSeatList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainSeatQueryVO> lists = BeanUtil.copyToList(dailyTrainSeatList, DailyTrainSeatQueryVO.class);
        PageVO<DailyTrainSeatQueryVO> pageVO = new PageVO<>();
        pageVO.setList(lists);
        pageVO.setTotal(pageInfo.getTotal());

        return pageVO;
    }

    public void deleteDailyTrainSeat(Long id) {
        dailyTrainSeatMapper.deleteByPrimaryKey(id);
    }

    /**
     * 生成date日期的trainCode的车次座位的数据
     * @param trainCode
     * @param date
     */
    public void GenerateDailyTrainSeat(String trainCode, Date date){
        LOG.info("生成日期【{}】的车次【{}】座位信息开始", DateUtil.formatDate(date),trainCode);

        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andDateEqualTo(date);
        dailyTrainSeatMapper.deleteByExample(dailyTrainSeatExample);

        List<TrainSeat> trainSeats = trainSeatService.SelectByTrainCode(trainCode);

        List<TrainStation> trainStations = trainStationService.SelectByTrainCode(trainCode);
        String sell = StrUtil.fillBefore("", '0', trainStations.size() - 1);

        if(CollUtil.isEmpty(trainSeats)){
            LOG.info("改车次没有座位信息，生成结束");
            LOG.info("生成日期【{}】的车次【{}】座位信息结束", DateUtil.formatDate(date),trainCode);
            return;
        }

        for (TrainSeat trainSeat : trainSeats) {
            DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(trainSeat, DailyTrainSeat.class);
            dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
            DateTime time = DateTime.now();
            dailyTrainSeat.setCreateTime(time);
            dailyTrainSeat.setUpdateTime(time);
            dailyTrainSeat.setDate(date);
            dailyTrainSeat.setSell(sell);
            dailyTrainSeatMapper.insert(dailyTrainSeat);
        }

        LOG.info("生成日期【{}】的车次【{}】座位信息结束", DateUtil.formatDate(date),trainCode);
    }

    /**
     * 根据日期 列车车次以及作为类型去查询相应的座位的数量 返回int类型的座位数量
     * 便于后续初始化余票信息时插入
     * @param trainCode
     * @param date
     * @param trainTypeCode
     * @return
     */
    public int CountSeatNumberByType(String trainCode, Date date, String trainTypeCode){
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andDateEqualTo(date)
                .andSeatTypeEqualTo(trainTypeCode);
        long nums = dailyTrainSeatMapper.countByExample(dailyTrainSeatExample);
        if(nums == 0L) return -1;
        return (int) nums;
    }
}
